var AMCOMMON = AMCOMMON || {};

AMCOMMON.rowsJsonField = function (rows, okey, nkey) {
    if (rows && rows.length > 0) {
        for (var i = 0; i < rows.length; i++) {
            AMCOMMON.objectField(rows[i], okey, nkey);
        }
    }
}

AMCOMMON.objectField = function (obj, okey, nkey) {
    if (obj[okey]) {
        obj[nkey] = JSON.parse(obj[okey]);
    }
}

AMCOMMON.formatValueToStorage = function (val) {
    var fs = val < 0
    val = fs ? val * -1 : val
    var rst = val
    if (val >= 1099511627776) {
        rst = (val / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
    } else if (val >= 1073741824) {
        rst = (val / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
    } else if (val >= 1048576) {
        rst = (val / (1024 * 1024)).toFixed(2) + ' MB';
    } else {
        rst = (val / 1024).toFixed(2) + ' KB';
    }
    rst = fs ? "-" + rst : rst
    return rst
}

AMCOMMON.formatValue = function (val, type) {
    switch (type) {
        case "storage":
            val = AMCOMMON.formatValueToStorage(val);
            break;
        case "percent":
            val = AMCOMMON.formatValueToPercent(val);
            break;
        case "cputime":
            val = AMCOMMON.formatValueToCpuTime(val);
            break;
        case "timeBySecond":
            val = AMCOMMON.formatSeconds(val);
            break;
        default:
            val = AMCOMMON.formatNumberToUnits(val);
            break;
    }
    return val;
}

AMCOMMON.formatSeconds = function (sec) {
    let ms = Math.floor((sec % 1) * 1000);
    let s = Math.floor(sec);
    let d = Math.floor(s / 86400);
    s %= 86400;
    let h = Math.floor(s / 3600);
    s %= 3600;
    let m = Math.floor(s / 60);
    s %= 60;
    return [
        d ? `${d}天` : '',
        h ? `${h}小时` : '',
        m ? `${m}分` : '',
        s ? `${s}秒` : '',
        ms ? `${ms}毫秒` : ''
    ].filter(Boolean).join('');
}

AMCOMMON.formatValueToPercent = function (val) {
    if (typeof val === "number") {
        return (val * 1).toFixed(2) + '%'
    }
    return val
}

AMCOMMON.formatValueToCpuTime = function (val) {
    // 判断正负
    var fs = val < 0;
    val = fs ? val * -1 : val; // 取绝对值
    var rst = val;
    if (val >= 3600000000000) { // 超过3600秒（1小时）
        rst = (val / 3600000000000).toFixed(2) + ' h';
    } else if (val >= 60000000000) { // 超过60秒（1分钟）
        rst = (val / 60000000000).toFixed(2) + ' min';
    } else if (val >= 1000000000) { // 超过1秒
        rst = (val / 1000000000).toFixed(2) + ' s';
    } else if (val >= 1000000) { // 超过1毫秒
        rst = (val / 1000000).toFixed(2) + ' ms';
    } else if (val >= 1000) { // 超过1微秒
        rst = (val / 1000).toFixed(2) + ' μs';
    } else { // 小于1微秒
        rst = val + ' ns';
    }
    // 如果原值为负，则加上负号
    rst = fs ? "-" + rst : rst;
    return rst;
}

AMCOMMON.formatNumberToUnits = function (val) {
    // 判断正负
    var fs = val < 0;
    val = fs ? val * -1 : val; // 取绝对值
    var rst = val;

    if (val >= 100000000) {
        rst = (val / 100000000).toFixed(2) + ' 亿';
    } else if (val >= 10000) {
        rst = (val / 10000).toFixed(2) + ' 万';
    } else { // 小于1000
        rst = val
    }

    // 如果原值为负，则加上负号
    rst = fs ? "-" + rst : rst;
    return rst;
}

AMCOMMON.formatMetricsData = function (payload, group, scope) {
    for (m in group.metrics ?? []) {
        let metric = group.metrics[m]
        metric.uuid = `chart_${group.name}_m${m}`
        if (!scope[metric.uuid + "_lastUpdateTime"]) scope[metric.uuid + "_lastUpdateTime"] = Date.now()
        if (!scope[metric.uuid + "_lines"]) scope[metric.uuid + "_lines"] = []
        if (!scope[metric.uuid + "_series"]) scope[metric.uuid + "_series"] = []
        let lineData = {}
        if (metric.key && !metric.mergeKeys) metric.mergeKeys = [metric.key]
        for (k in metric.mergeKeys ?? []) {
            let key = metric.key
            let mergeKey = metric.mergeKeys[k]
            let serieName = metric.name;
            let row = payload.rows[0]
            let evalScript = metric.serieNameTmp
            if (evalScript == "" || evalScript == null) {
                evalScript = "${key}-${serieName}"
            }
            for (i in payload.rows ?? []) {
                let row = payload.rows[i]
                let lineName = eval('`' + evalScript + '`')
                if (!lineData[lineName]) {
                    lineData[lineName] = {
                        name: lineName,
                        type: 'line', smooth: true, data: []
                    }
                }
                lineData[lineName].data.push([row[group.time ?? "time"], row[mergeKey]])
            }
            scope[metric.uuid + "_lines"].length = 0
            scope[metric.uuid + "_series"].length = 0
            for (k in lineData) {
                scope[metric.uuid + "_lines"].push(k)
                scope[metric.uuid + "_series"].push(lineData[k])
            }
            scope[metric.uuid + "_lastUpdateTime"] = Date.now()
        }
    }
}

AMCOMMON.testfunction = function (that) {
    // AMCOMMON.testfunction(this)
    console.info(that)
    console.info(that.amisStore.stores)
    let data = {}
    for (key in that.amisStore.stores) {
        data[key] = {
            key: key,
            path: that.amisStore.stores[key].path,
            old: that.amisStore.stores[key]
        }
    }
    console.info(data)
}